# -*- coding: utf-8 -*-

import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class SichuanChengduPolicy(BaseTaxPolicySpider):
    name = 'sichuan_chengdu_jksj_policy'

    province = '四川省'
    city = '成都市'
    # county = '滑县'
    park = ''

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    # "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,  # 为 None 失效
                    "scrapy.downloadermiddlewares.retry.RetryMiddleware": None,  # 为 None 失效
                    "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": 550,
                    "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": 551,
                    "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": 552,
                    'components.middlewares.downloadmiddlewares.private.rs_6_middlewares.Rs6RetryMiddleware': 553,
                    # **downloader_middlewares
                },
                "DOWNLOAD_TIMEOUT": 100
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['成都市发展和改革委员会', "", "https://cddrc.chengdu.gov.cn/cdsfzggw/qtwj/DepartmentalDocumentsList.shtml?classId=1580116519959474177"],
            ['成都市发展和改革委员会', "", "https://cddrc.chengdu.gov.cn/cdsfzggw/qtwj/DepartmentalDocumentsList.shtml?classid=1588371990657957890"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_request, meta={'item': item}, dont_filter=True)

    def parse_request(self, response, **kwargs):
        meta = response.meta
        classid = response.url.split('classId=')[-1].split('classid=')[-1]
        params = {
            "current": 1,
            "classId": classid,
            "size": 100
        }
        url = "/gkml/api/sfgwApi/listPage?"
        meta['url'] = url
        meta['params'] = params
        yield response.follow(url + urllib.parse.urlencode(params), callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = meta.get('item')
        datas = response.json()['data']
        elem_list = datas['records']
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem['detailInfoUrl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['checkTime']
            item['title'] = elem['name']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})

        pages = datas['pages']
        url = meta.get('url')
        params = meta.get('params')
        page = params.get('current') or 1
        page = int(page)
        print(response.url, pages, "page:", page)
        if page < pages:
            page += 1
            params['current'] = str(page)
            yield response.follow(url + urllib.parse.urlencode(params), callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        # item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("//div[@class='ele']/div[contains(text(), '发布日期')]/following-sibling::div/text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        # print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_chengdu_jksj_policy".split())
